package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已完成登陆
 *
 * @author Xiao
 * @date 2021/9/22
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求URI
        String requestURI = request.getRequestURI();
//        log.info("拦截到请求：{}", requestURI);
        //定义要放行的资源
        String[] urls = {
                "/backend/**", "/front/**", "/employee/login",
                "/common/**", "/user/sendMsg", "/user/login",
                "/doc.html", "/webjars/**",
                "/swagger-resources", "/v2/api-docs"
        };
        //判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //如果不需要处理，直接放行
        if (check) {
//            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //判断登陆状态，如果已登录，直接放行
        //判断后台管理端登录状态
        if (request.getSession().getAttribute("loginEmp") != null) {
            Long loginEmpId = (Long) request.getSession().getAttribute("loginEmp");
            log.info("用户已登录，empId：{}", loginEmpId);
            //获取当前请求的线程id
            /*long id = Thread.currentThread().getId();
            log.info("线程id：{}", id);*/
            //将当前用户登录的id封装到BaseContext
            BaseContext.setCurrentId(loginEmpId);
            filterChain.doFilter(request, response);
            return;
        }
        //判断前台用户端登录状态
        if (request.getSession().getAttribute("loginUserId") != null) {
            Long loginUserId = (Long) request.getSession().getAttribute("loginUserId");
            log.info("用户已登录，userId：{}", loginUserId);
            //将当前用户登录的id封装到BaseContext
            BaseContext.setCurrentId(loginUserId);
            filterChain.doFilter(request, response);
            return;
        }
        //如果未登录，判断是否为异步请求
//        log.info("用户未登录");
//        log.info("Header-Referer:{}", request.getHeader("Referer"));
        // 如果是不是异步请求，重定向到登录界面
        if (!isAjaxRequest(request)) {
            if (PATH_MATCHER.match("/backend/**", requestURI)) {
                response.sendRedirect("http://localhost:8080/backend/page/login/login.html");
                return;
            }
            response.sendRedirect("http://localhost:8080/front/page/login.html");
            return;
        }
        // 如果是异步请求，通过输出流向客户端页面响应数据
        String data = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(data);
    }

    /**
     * 路径匹配：检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是异步请求
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains("application/json")) {
            return true;
        }
        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
            return true;
        }
        String uri = request.getRequestURI();
        if (StringUtils.containsIgnoreCase(uri, ".json")
                || StringUtils.containsIgnoreCase(uri, ".xml")) {
            return true;
        }
        String ajax = request.getParameter("__ajax");
        if (StringUtils.containsIgnoreCase(ajax, "json") ||
        StringUtils.containsIgnoreCase(ajax, "xml")){
            return true;
        }
        return false;
    }
}
